package com.example.exportsql.controller;

import com.example.exportsql.entity.TableStruct;
import com.example.exportsql.mapper.MyMapper;
import com.fasterxml.jackson.core.TSFBuilder;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * @author 廖半仙
 * @date 2025/5/21
 */
@RestController
@RequestMapping("/api")
public class MyController {

    @Autowired
    private MyMapper tableMapper;

    @RequestMapping("/list")
    public List<String> list(){
        return tableMapper.getAllTables();
    }

    @GetMapping("/download")
    public void downSeg(HttpServletResponse response){
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("表结构注释说明"+ LocalDate.now().toString(), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".docx");

            // 创建文档
            XWPFDocument document = new XWPFDocument();

            //设置标题
            XWPFStyles styles = document.createStyles();
            String heading1StyleId = "heading1";
            addCustomHeadingStyle(styles, heading1StyleId, "标题 1", 1);

            tableMapper.getAllTables().forEach(temp ->{
                //生成标题
                XWPFParagraph title1Paragraph = document.createParagraph();
                title1Paragraph.setStyle(heading1StyleId);
                XWPFRun title1Run = title1Paragraph.createRun();
                title1Run.setText(temp);

                String database = tableMapper.getDatabase();
                //生成表头
                List<TableStruct> tableInfo = tableMapper.getTableInfo(temp, database);
                XWPFTable table = document.createTable(tableInfo.size() + 1, 6);
                table.setWidth("100%");
//                table.getRow(0).getCell(0).setText("序号");
                table.getRow(0).getCell(0).setText("字段描述");
                table.getRow(0).getCell(1).setText("字段名称");
                table.getRow(0).getCell(2).setText("字段类型");
                table.getRow(0).getCell(3).setText("是否为空");
                table.getRow(0).getCell(4).setText("主键");
                table.getRow(0).getCell(5).setText("默认值");

                //生成表内容  第0行已经设置为表头，因此我们需要从第一行开始
                for (int row = 0; row < tableInfo.size(); row++) {
//                    table.getRow(row +1 ).getCell(0).setText(Integer.toString(row));
                    table.getRow(row +1 ).getCell(0).setText(tableInfo.get(row).getComment());
                    table.getRow(row +1 ).getCell(1).setText(tableInfo.get(row).getField());
                    table.getRow(row +1 ).getCell(2).setText(tableInfo.get(row).getType());
                    table.getRow(row +1 ).getCell(3).setText(tableInfo.get(row).getTnull());
                    table.getRow(row +1 ).getCell(4).setText(tableInfo.get(row).getTkey());
                    table.getRow(row +1 ).getCell(5).setText(tableInfo.get(row).getTdefault());
                }
            });

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write(byteArrayOutputStream);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.flush();
            outputStream.close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void addCustomHeadingStyle(XWPFStyles styles, String styleId, String styleName, int headingLevel) {
        CTStyle ctStyle = CTStyle.Factory.newInstance();
        ctStyle.setStyleId(styleId);
        CTString styleNameString = CTString.Factory.newInstance();
        styleNameString.setVal(styleName);
        ctStyle.setName(styleNameString);

        CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
        indentNumber.setVal(BigInteger.valueOf(headingLevel));

        CTPPr ppr = CTPPr.Factory.newInstance();
        ppr.setOutlineLvl(indentNumber);
        ctStyle.setPPr(ppr);

        XWPFStyle style = new XWPFStyle(ctStyle);
        styles.addStyle(style);
    }

}
